package org.lsda.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.lsda.util.Util;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

/**
 * Servlet implementation class ListPrograms
 */
@WebServlet("/ListPrograms")
public class ListPrograms extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ListPrograms() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		int jtPageSize = Integer.parseInt(request.getParameter("jtPageSize"));
		int jtStartIndex =Integer.parseInt(request.getParameter("jtStartIndex"));
		String jtSorting = request.getParameter("jtSorting");
		String[] arr = jtSorting.split("\\s+");
		String temp="";
		for(String a:arr){
			if(a.equals("Category"))
				temp+=" "+"CATEGORY";
			else if(a.equals("PrgName"))
				temp+=" "+"PRG_NAME";
			else if(a.equals("Author"))
				temp+=" "+"PRG_AUTHOR";
			else if(a.equals("PrgDesc"))
				temp+=" "+"PRG_DESC";
			else
				temp+=" "+a;
		}
		Connection conn = null;
		JsonObject json = new JsonObject();
		json.addProperty("Result", "OK");
		int totalCount = 0;
		try {
			conn = Util.getConnection();
			totalCount = Util.countPrograms(conn);
			JsonArray array = Util.listPrograms(conn,jtPageSize,jtStartIndex,temp);
			json.add("Records", array);
			json.addProperty("TotalRecordCount", totalCount);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			json.addProperty("Result", "ERROR");
			json.addProperty("Message", e.getMessage());
			e.printStackTrace();
		} finally{
			try{
				conn.close();
			}catch(Throwable ignore){}
		}
		
		
		PrintWriter writer = response.getWriter();
//		System.out.println(json.toString());
		writer.write(json.toString());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request,response);
	}

}
